﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;

namespace OpenCvSharpWinform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 打开图像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 打开图像ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog op3=new OpenFileDialog();
            op3.Multiselect = true; // 设置图片多选
            op3.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"; // 设置选中图像的格式
            if (op3.ShowDialog() == DialogResult.OK) 
            {
                pictureBox1.Image=Image.FromFile(op3.FileName); // 加载图像到pictureBox1控件上
                // Image格式转换成Bitmap格式方法
                pic2.bitmap1=new Bitmap(pictureBox1.Image);
            }
        }

        /// <summary>
        /// 灰度变换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 将bitmap格式转换成Mat格式
            Mat m1 = OpenCvSharp.Extensions.BitmapConverter.ToMat(pic2.bitmap1);
            m1 = m1.CvtColor(ColorConversionCodes.BGR2GRAY); // 将图像转换单通道灰度图
            Scalar scalar = Cv2.Mean(m1); // 计算灰度图平均值
            Cv2.Threshold(m1, m1, scalar.Val0, 255, ThresholdTypes.Binary); // 图像二值化 - 二值图的好处是去掉底色背景的

            pic2.bitmap1 = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(m1); // 将Mat格式图像转换成Bitmap格式
            pictureBox2.Image=pic2.bitmap1;  // bitmap图像可以直接赋值给Image
        }
    }
}
